package com.videomeetting.legend.videomeetting.activity.fragment;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.videomeetting.legend.videomeetting.R;
import com.videomeetting.legend.videomeetting.activity.adapater.FileListAdapater;
import com.videomeetting.legend.videomeetting.activity.base.BaseApplication;
import com.videomeetting.legend.videomeetting.activity.bean.VideoBean;
import com.videomeetting.legend.videomeetting.activity.layoutmanager.MyLinearLayoutManager;
import com.videomeetting.legend.videomeetting.activity.utils.MyUtils;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by legend on 18-6-29.
 */

public class FilesFragment extends Fragment implements View.OnClickListener{
    RecyclerView filesRv;
    FileListAdapater adapater;
    List<VideoBean> videoBeans = null;
    List<VideoBean> localVideos;
    List<VideoBean> extralVideos;
    private int local=0;
//    List<String> fileNames = new ArrayList<>();//Arrays.asList("2014-03-20-1103.mp4","2014-06-26-1489.mp4","2014-07-10-0026.mp4","2014-12-06-0398.mp4");
//    List<String> fileTimes = new ArrayList<>();//Arrays.asList("26","48","55","96");
//    List<String> fileLenghts = new ArrayList<>();//Arrays.asList("1032","2023","2688","5686");
    MediaMetadataRetriever retriever;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        retriever = new MediaMetadataRetriever();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
                }else {
                    Log.i("legend", "run localVideos: "+Uri.parse("file://" + "/storage"));
                    Log.i("legend", "run extralVideos: "+MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                    //内部储存
//                    localVideos=getFileName(new File(MediaStore.Video.Media.EXTERNAL_CONTENT_URI.toString()).listFiles());
                    localVideos = MyUtils.queryLocalVideo(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI,0);//getStorageDirectory
//                    localVideos = getFileName(new File("/storage").listFiles());
//                    extralVideos = queryLocalVideo(getActivity(), Uri.parse("file://" + "storage"));//Uri.parse("file://" + "/storage")
                    Log.i("legend", "run: localVideos: "+localVideos.size());
//                    Log.i("legend", "run: extralVideos: "+extralVideos.size());
                }
            }
        }).start();

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 123:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    localVideos = MyUtils.queryLocalVideo(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI,0);
//                    localVideos = getFileName(new File("/storage").listFiles());
                }else {
                    Toast.makeText(getActivity(), "You denied the permission", Toast.LENGTH_SHORT).show();
                }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        updateMediaDataBase(Environment.getExternalStorageDirectory().getAbsolutePath());
        if (localVideos!=null) {
            adapater = new FileListAdapater(getActivity(), localVideos);
//            adapater.setCallback(callback);
        }
        else {
            adapater = new FileListAdapater(getActivity(), null);
//            adapater.setCallback(callback);
        }
        MyLinearLayoutManager manager=new MyLinearLayoutManager(getContext());
        filesRv.setAdapter(adapater);
        filesRv.setLayoutManager(manager);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_files,container,false);
        filesRv = (RecyclerView) view.findViewById(R.id.fragment_files_rv);
        Button localButton = (Button) view.findViewById(R.id.fragment_files_local);
        Button extralButton = (Button) view.findViewById(R.id.fragment_files_extral);
        Button copyButton = (Button) view.findViewById(R.id.fragment_files_copy);
        Button deteleButton = (Button) view.findViewById(R.id.fragment_files_detele);
//        ChooseAllCallback callback = new ChooseAllCallback() {
//            @Override
//            public void chooseAll() {
//                ToastUtils.showShort("全选");
//                adapater.setChooseList(adapater.getVideoBeans());
//            }
//
//            @Override
//            public void noChoose() {
//                ToastUtils.showShort("全不选");
//                adapater.getChooseList().clear();
//            }
//        };

        localButton.setOnClickListener(this);
        extralButton.setOnClickListener(this);
        copyButton.setOnClickListener(this);
        deteleButton.setOnClickListener(this);
        return view;
    }

    /**
     * 判断设备是否有U盘
     * @return
     */
    public  boolean isExtralStorage(){
        boolean usb = false;
        File storage = new File("storage");
        if (storage.exists()){
            File[] files = storage.listFiles();
            for (int i=0;i<files.length;i++) {
                if (storage.canRead()) {
                    if (files[i].getName().equals("usbport1")||files[i].getName().equals("usbport4")){//storage.getName().equals(Environment.getExternalStorageDirectory().getName())
                        usb = true;
                    }
                }
            }

        }
        return usb;
    }

    /**
     * 获取制定MP4文件并返回一个列表
     * @param files
     * @return
     */

    private List<VideoBean> getFileName(File[] files) {
        List<VideoBean> videoBeans = new ArrayList<>();
        if (files != null) {// 先判断目录是否为空，否则会报空指针
            String fileName = null;
            for (File file : files) {
                VideoBean bean = new VideoBean();
                if (file.isDirectory()) {
                    getFileName(file.listFiles());
                } else {
                    fileName = file.getName();
                    if (fileName.endsWith(".mp4")) {
                        bean.setName(fileName);
                        bean.setLenght(String.valueOf(file.length()/(1024*1024)));
                        retriever.setDataSource(file.getPath()); //在获取前，设置文件路径（应该只能是本地路径）
                        String duration =  retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                        bean.setTime(String.valueOf((int)Long.parseLong(duration)/(60000)));
                        bean.setFilePath(file.getPath());
                        videoBeans.add(bean);
                    }
                }
            }
        }
        return videoBeans;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.fragment_files_local:
                local=0;
                adapater.setVideoBeans(localVideos);
                adapater.notifyDataSetChanged();
                break;
            case R.id.fragment_files_extral:
                local=1;
                boolean extralStorage = isExtralStorage();
                if (extralStorage){
                    extralVideos = MyUtils.queryLocalVideo(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI,1);
                }else {
                    Toast.makeText(getActivity(),"请插入U盘",Toast.LENGTH_SHORT).show();
                }
                adapater.setVideoBeans(extralVideos);
                adapater.notifyDataSetChanged();
                break;
            case R.id.fragment_files_copy:
                List<VideoBean> chooseList = adapater.getChooseList();
                ToastUtils.showShort("拷贝"+chooseList.size()+"");
                break;
            case R.id.fragment_files_detele:
                List<VideoBean> chooseList1 = adapater.getChooseList();
                for (int i=0;i<chooseList1.size();i++){
                    File file = new File(chooseList1.get(i).getFilePath());
                    if (file.exists()){
                        file.delete();
                    }
                }
//                this.getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, MediaStore.Video.Media.EXTERNAL_CONTENT_URI));
//                File file = new File(String.valueOf(MediaStore.Video.Media.EXTERNAL_CONTENT_URI));
//                updateMediaDataBase(Environment.getExternalStorageDirectory().getAbsolutePath());
//                this.getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, MediaStore.Video.Media.EXTERNAL_CONTENT_URI));
                if (local==0){
                    adapater.getChooseList().clear();
                    adapater.setVideoBeans(MyUtils.queryLocalVideo(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI,0));
                    adapater.notifyDataSetChanged();
                }else {
                    adapater.setVideoBeans(MyUtils.queryLocalVideo(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI,1));
                    adapater.getChooseList().clear();
                    adapater.notifyDataSetChanged();
                }
                break;
        }

    }


    private void updateMediaDataBase(String filename) {
        int currentApiVersion = android.os.Build.VERSION.SDK_INT;// 获得当前sdk版本
        if (currentApiVersion < 19) {
            getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + filename)));
        } else {
            MediaScannerConnection.scanFile(getContext(), new String[] { filename },
                    null, new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });
        }
    }


//    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
//
//retriever.release(); //释放
//if(!TextUtils.isEmpty(duration)){
//        long dur = Long.parseLong(duration);
//    }
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 300) {
//            Cursor cursor1 = getActivity().getContentResolver().query( data.getData(), new String[] { MediaStore.Video.Media.DISPLAY_NAME,
//                    MediaStore.Video.Media.SIZE,MediaStore.Video.Media.DURATION,MediaStore.Video.Media.DATA }, null, null, null );
//            if ( null != cursor1 ) {
//                cursor1.getString(0);//获取视频的名字
//                cursor1.getLong(1);//获取视频的大小
//                cursor1.getLong(3);//获取视频的时长
//                cursor1.getLong(4);//获取视频的地址 ，顺序是和上面的对应的
//            }
//            cursor1.close();
//        }
//
//    }
}
